package client;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.util.LinkedList;

import javax.swing.JPanel;

import ui.IWritingPanel;

public class SingleConversation implements ISingleConversation{

	private BufferedWriter bw;
	private String nick;
	private LinkedList<String> singleConversationList=new LinkedList<String>();
	private HashMap<String,SConversationFrame> frameMap = new HashMap<String,SConversationFrame>();
	private IWritingPanel writingPanel;
	
	public SingleConversation(String nick, BufferedWriter bw,IWritingPanel iP) {
		this.bw=bw;
		this.nick=nick;
		this.writingPanel=iP;
		
	}
	
	
	public void generateConversation(String reciever){
		
		if(singleConversationList.contains(reciever)){
		
			return;
		
		}
		
		final SConversationFrame conversationFrame = new SConversationFrame(reciever);
		
		conversationFrame.addWindowListener(new WindowListener() {
			
			@Override
			public void windowClosing(WindowEvent arg0) {
				
				singleConversationList.remove(conversationFrame.getTitle());
				frameMap.remove(conversationFrame);

			}

			@Override
			public void windowActivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowIconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowOpened(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		frameMap.put(conversationFrame.getTitle(),conversationFrame);
		singleConversationList.add(reciever);
		
		chatPanelGenerator(conversationFrame,writingPanel.writingGenerator(nick, bw, "@"+frameMap.get(reciever).getTitle()+" "));
				
	}

	public void chatPanelGenerator(SConversationFrame conversationFrame,Component writingPanel) {
		
		JPanel chatpanel = new JPanel();
		chatpanel.setLayout(new BorderLayout());
		conversationFrame.add(chatpanel,BorderLayout.CENTER);
		conversationFrame.add((Component) writingPanel,BorderLayout.SOUTH);
	
	}
	
	public void textAppenderSender(String read){
		
		frameMap.get(read.substring(0,read.indexOf(" "))).setReadingField(read.substring(0,read.length()));
		
	}

	public void textAppenderReceiver(String read){
		
		frameMap.get(read.substring(0,read.indexOf(" "))).setReadingField(read.substring(read.indexOf(" ")+1,read.length()));
		
	}
	
	
	
}
